package com.jfsnpm.common;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.snaker.engine.entity.HistoryOrder;
import org.snaker.engine.entity.HistoryTask;
import org.snaker.engine.entity.Process;
import org.snaker.engine.entity.Task;
import org.snaker.jfinal.plugin.SnakerPlugin;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfsnpm.authority.AuthorityCheck;
import com.jfsnpm.plugin.bjui.BjuiRender;

public class FlowTool {
	/**
	 * 显示流程任务
	 * @param userid
	 * @param taskid
	 * @param c
	 */
	public static void flowview(String userid,String taskid,Controller c){
		//权限判断
		if(!AuthorityCheck.getTaskAuthoriy(userid, taskid)){c.render(BjuiRender.code(401));return;}
		c.setAttr("taskid", taskid);
		c.setAttr("historyTasks", getHistoryTasks(SnakerPlugin.getEngine().query().getTask(taskid).getOrderId()));
		c.render("task_view.html");//在FlowController中调用本function
	}
	/**
	 * 显示流程任务的表单部分
	 * @param userid
	 * @param taskid
	 * @param c
	 */
	public static void flowviewform(String userid,String taskid,Controller c){
		//权限判断
		if(!AuthorityCheck.getTaskAuthoriy(userid, taskid)){c.render(BjuiRender.code(401));return;}
		//获得本任务的表单路径(文件夹名(xxx) 即 数据库表名(form_xxx)) 表单名称 表单id
		String orderid="";
		String formname="";
		Task taskon = SnakerPlugin.getEngine().query().getTask(taskid);
		if(taskon==null){
			HistoryTask task = SnakerPlugin.getEngine().query().getHistTask(taskid);
			orderid=task.getOrderId();
			formname=task.getActionUrl();
			if(StringUtils.isBlank(formname)){
				formname = task.getTaskName();
			}
		}else{
			orderid=taskon.getOrderId();
			formname=taskon.getActionUrl();
			if(StringUtils.isBlank(formname)){
				formname = taskon.getTaskName();
			}
		}
		HistoryOrder order = SnakerPlugin.getEngine().query().getHistOrder(orderid);
		Process process = SnakerPlugin.getEngine().process().getProcessById(order.getProcessId());
		String formpath=process.getInstanceUrl();
		
		//TODO:暂时用order id作为表单主键，后续需改为从Variable字段获取
		String formid = orderid;
		if(StringUtils.isBlank(formpath)){
			formpath = process.getName();
		}
		Record formdata = Db.findFirst("select * from form_"+formpath+" where id = ?", formid);
		
		if(AppTool.tableIsExists("form_"+formpath+"_detail")){
			List<Record> datalist = Db.find("select * from form_"+formpath+"_detail where masterid = ?", formid);
			if(datalist != null && datalist.size() > 0){
				c.setAttr("datalist", datalist);
			}
		}
		
		
		
		c.setAttr("orderid", orderid);
		c.setAttr("taskid", taskid);
		c.setAttr("formpath", formpath);
		c.setAttr("formdata", formdata);
		c.render("form/"+formpath+"/"+formname+".html");
	}
	/**
	 * 获取经过处理过的历史任务列表
	 * @param orderid
	 * @return
	 */
	public static List<Record> getHistoryTasks(String orderid){
		List<Record> historytasks = Db.find(AppSql.getsql("Flow.getHistoryTasks"),orderid);
		for(Record historytask:historytasks){
			String histaskid = historytask.getStr("id");
			Map<String, Object> historyargs = SnakerPlugin.getEngine().query().getHistTask(histaskid).getVariableMap();
			historytask.set("flow_operate", historyargs.get("flow_operate") );
			historytask.set("flow_operate_mark", historyargs.get("flow_operate_mark") );
		}
		return historytasks;
	}
	/**
	 * 显示流程实例
	 * @param userid
	 * @param orderid
	 * @param c
	 */
	public static void orderview(String userid,String orderid,Controller c){
		c.setAttr("orderid", orderid);
		c.setAttr("orderstatus", SnakerPlugin.getEngine().query().getHistOrder(orderid).getOrderState());
		c.setAttr("historyTasks", getHistoryTasks(orderid));
		c.render("order_view.html");//在FlowController中调用本function
	}
	/**
	 * 显示流程实例的表单部分
	 * @param userid
	 * @param orderid
	 * @param c
	 */
	public static void flowviewformbyorderid(String userid,String orderid,Controller c){
		//获得本任务的表单路径(文件夹名 即 数据库表名) 表单名称 表单id
		HistoryOrder order = SnakerPlugin.getEngine().query().getHistOrder(orderid);
		Process process = SnakerPlugin.getEngine().process().getProcessById(order.getProcessId());
		String formpath=process.getInstanceUrl();
		String formname="readonly";
		//TODO:暂时用order id作为表单主键，后续需改为从Variable字段获取
		String formid = orderid;
		if(StringUtils.isBlank(formpath)){
			formpath = process.getName();
		}
		Record formdata = Db.findFirst("select * from form_"+formpath+" where id = ?", formid);
		
		if(AppTool.tableIsExists("form_"+formpath+"_detail")){
			List<Record> datalist = Db.find("select * from form_"+formpath+"_detail where masterid = ?", formid);
			if(datalist != null && datalist.size() > 0){
				c.setAttr("datalist", datalist);
			}
		}
		
		c.setAttr("orderid", orderid);
		c.setAttr("taskid", "");
		c.setAttr("formpath", formpath);
		c.setAttr("formdata", formdata);
		c.render("form/"+formpath+"/"+formname+".html");
	}
	
	public static Map<String, Object> setFlowUsers(Map<String, Object> args){
		Map<String, Object> arg = args;
		arg.put("user_parent", getParent(arg.get("user").toString()));
		arg.put("user_gm", getDeptUsers("总经理"));
		arg.put("user_pur", getDeptUsers("采购部"));
		
		return arg;
	}
	private static String getDeptUsers(String deptName) {
		String temp = "";
		List<Record> listsmfgmanager = Db.find(AppSql.getsql("pm.getDeptUserByName"),deptName);
		for(Record list:listsmfgmanager){
			temp = temp + list.getStr("userid") + ",";
		}
		if(!temp.isEmpty()){
			temp = temp.substring(0, temp.length()-1);
		}else{
			temp = "admin";
		}
		return temp;
	}
	private static String getParent(String userid){
		String parentid="";
		
		List<Record> listsmfgmanager = Db.find(AppSql.getsql("pm.getParentUsers"),userid);
		for(Record list:listsmfgmanager){
			parentid = parentid + list.getStr("userid") + ",";
		}
		if(!parentid.isEmpty()){
			parentid = parentid.substring(0, parentid.length()-1);
		}else{
			parentid = "admin";
		}
		return parentid;
	}
	
	
	
	
}
